<template>
    <div>
        <page-layout
            title="User"
            :subtitle="!!user.id ? 'Update' : 'Create'"
            :button-title="!!user.id ? 'Update' : 'Create'"
            @save="save"
            @cancel="back"
        >

        <v-form v-model="formValid" ref="form">
            <card title="Basic Information">
                <v-row>
                    <v-col cols="12" sm="6" md="6">
                        <v-text-field
                            outlined
                            dense
                            v-model="user.first_name"
                            label="First Name *"
                            :rules="[v => !!v || 'First Name is required']"
                        />
                    </v-col>
                    <v-col cols="12" sm="6" md="6">
                        <v-text-field
                            outlined
                            dense
                            v-model="user.last_name"
                            label="Last Name *"
                            :rules="[v => !!v || 'Last Name is required']"
                        />
                    </v-col>
                    <v-col cols="12" sm="6" md="6">
                        <v-text-field
                            outlined
                            dense
                            type="email"
                            v-model="user.email"
                            label="Email"
                        />
                    </v-col>
                    <v-col cols="12" sm="6" md="6">
                        <v-select
                            multiple
                            outlined
                            dense
                            :items="roles"
                            item-text="name"
                            item-value="id"
                            v-model="roleIds"
                            label="Role"
                        />
                    </v-col>
                </v-row>
            </card>
            <br><br>

            <card title="login credential">
                <v-row>
                    <v-col cols="12" sm="6" md="6">
                        <v-text-field
                            outlined
                            dense
                            :disabled="!!user.id"
                            v-model="user.username"
                            label="Username *"
                            :rules="[v => !!v || 'Username is required']"
                        />
                    </v-col>
                    <v-col cols="12" sm="6" md="6">
                        <v-text-field
                            outlined
                            dense
                            v-model="user.password"
                            :label="!!user.id ? 'New Password' : 'Password'"
                            :append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
                            :type="showPassword ? 'text' : 'password'"
                            @click:append="showPassword = !showPassword"
                            required
                        />
                    </v-col>
                </v-row>
            </card>
            <br><br>
        </v-form>
        </page-layout>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { User } from '@/type/Auth';
import { Role } from '@/type/Permission';
import store from '@/store/Index';
import removeModelRelationship from '@/helpers/ObjectHelper';
import PageLayout from '@/components/PageLayout.vue';
import Card from '@/components/card/Card.vue';
import { toJS } from 'mobx';

export default Vue.extend({
    name: 'UserPage',
    components: {
        PageLayout,
        Card,
    },
    data(): {
        store: any;
        showPassword: boolean;
        formValid: boolean;
        // selections
        // data
        user: User;
        roleIds: number[];
        } {
        return {
            store,
            formValid: false,
            showPassword: false,
            user: {
                name: '',
                first_name: '',
                username: '',
                email: '',
                password: '',
            },
            roleIds: [],
        };
    },
    computed: {
        getId(): string | number {
            return this.user.id || this.$route.params.id;
        },
        roles(): Role[] {
            return toJS(store.permission.roles);
        },
    },
    async mounted() {
        if (!this.getId || Number.isNaN(parseInt(this.getId as string, 10))) return;
        store.loader.run(async () => {
            await Promise.all([
                this.fetch(this.getId as number),
                store.permission.getRoles({ perPage: Number.MAX_SAFE_INTEGER }),
            ]);
        });
    },
    methods: {
        validate() {
            return (this.$refs.form as any).validate();
        },
        async fetch(id: number) {
            const user = await store.user.getUser(id);
            this.roleIds = (user.roles as Role[]).map((r) => r.id as number);
            this.user = removeModelRelationship(user);
        },
        async save() {
            if (!this.validate()) {
                store.alert.show('Please ensure to fill in the required fields', 'warning');
                return;
            }

            const isCreate = !this.user.id;

            store.loader.run(async () => {
                const {
                    user,
                } = this;

                const newUser = await store.user.saveUser(user, this.roleIds);
                await this.fetch(newUser.id as number);
                await store.user.logoutUser(newUser.id as number);
                store.alert.show(`The user information are ${isCreate ? 'created' : 'updated'} successfully!`, 'success');
                this.back();
            });
        },
        back() {
            this.$router.back();
        },
    },
});
</script>

<style scoped>
    .v-input > .v-input-control > .v-input-slot > .v-text-field__slot > input > ::-webkit-inner-spin-button, ::-webkit-calendar-picker-indicator {
        display: none;
        -webkit-appearance: none;
    }
</style>
